<?php
namespace Common\Controller;

use Common\Controller\AppframeController;
use Think\Controller;

class AppbaseController extends Controller
{

    protected $uploadPre; //上传保存前缀
    protected $pageLimit;  //分页每页数量（通常）
    const SERVICE_MAINTENANCE = 1; //养护
    const SERVICE_HELP = 2;  //应急呼救
    const SERVICE_CLEAN = 3; //洗车
    const SERVICE_COMPENSATE = 4;  //理赔

    /**
     * 初始化函数
     */
    public function _initialize()
    {
        $this->uploadPre = sp_get_host(). '/data/upload/';
        $this->pageLimit = 20;
    }

    /**
     * 将http形式的图片地址变为存入数据库的形式
     * @param $image
     * @return mixed
     */
    public function getSaveImageUrl($image){
        $image = str_replace($this->uploadPre,'',$image);
        return $image;
    }

    /**
     * @param int $status 未登录2,成功1，失败0
     * @param string $message 提示信息
     * @param mixed $jsonData 数据
     */
    protected function jsonReturn($status = 1, $message = "", $jsonData = "")
    {
        header('Content-Type:application/json; charset=utf-8');
        if ($jsonData!=="") {
            $data['data'] = $jsonData;
        }
        $data['status'] = intval($status);
        $data['message'] = $message;
        exit(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 不转义
     * @param int $status 未登录2,成功1，失败0
     * @param string $message 提示信息
     * @param mixed $jsonData 数据
     */
    protected function jsonUnslashesReturn($status = 1, $message = "", $jsonData = "")
    {
        header('Content-Type:application/json; charset=utf-8');
        if ($jsonData!=="") {
            $data['data'] = $jsonData;
        }
        $data['status'] = intval($status);
        $data['message'] = $message;
        exit(json_encode($data, JSON_UNESCAPED_SLASHES));
    }

    /**
     * curl的get请求
     *
     * @param string $url url网址
     * @param int $timeout 超时时间
     * @return false 或 执行返回结果
     */
    public static function requestByGet($url, $timeout = 2)
    {
        $retry = 1;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

        for ($i = 1; $i <= $retry; $i++) {
            $re = curl_exec($ch);

            if (is_string($re) && strlen($re)) {
                curl_close($ch);
            } else {
                if ($i == $retry) {
                    $curl_error = curl_error($ch);
                    curl_close($ch);
                }
            }

            if (!empty($re)) return $re;
        }
        error_log(__METHOD__ . ':' . $url . ':' . $curl_error);
        return false;
    }

    /**
     * curl的post请求
     *
     * @param string $url url网址
     * @param array $data post数组
     * @param int $timeout 超时时间
     * @return false 或 执行返回结果
     */
    public static function requestByPost($url, $data, $timeout = 3)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $result = curl_exec($ch);

        if ($result !== false) {
            curl_close($ch);
            return $result;//$result;
        } else {
            $curl_error = curl_error($ch);
            $_data = is_array($data) ? implode('&', $data) : $data;
            curl_close($ch);
            error_log(__METHOD__ . ':' . $url . '?' . $_data . ':' . $curl_error);
            return false;
        }
    }

    /**
     * 验证短信验证码
     * @param $phone string 电话
     * @param $sms string 短信验证码
     */
    protected function checkPhoneCode($phone, $sms)
    {
        $result = M('Sms')->where(['phone' => $phone])->find();
        if (!$result) {
            $this->jsonReturn(0, '请点击发送验证码');
        }
        $code = $result['sms'];
        if ($code != $sms) {
            $this->jsonReturn(0, '验证码不正确');
        }
        if ($result['expire_time'] < time()) {
            $this->jsonReturn(0, '验证码已过期，请重新发送');
        }
        M('Sms')->where(['phone' => $phone])->delete();
    }

    /**
     * 发送验证码
     * @param $phone
     */
    protected function sendSmsAndLog($phone)
    {
        $code = rand(1000, 9999);
        $content = '【一号点评】您的验证码是' . $code;
        $result = M('Sms')->where(['phone' => $phone])->find();
        $sendTime = strtotime(date("Y-m-d"));//当天0点
        //一个电话一天只能发10次验证码
        if ($result) {
            if (($result['create_time'] > $sendTime) && $result['count'] >= 10) {
                $this->jsonReturn(0, '验证码发送次数过多');
            }
        }
        //发送验证码
        $response = lt_send_sms($phone, $content);
        //发送成功
        if ($response) {
            $data['sms'] = $code;
            $data['expire_time'] = strtotime('+30 minutes');
            $data['create_time'] = time();
            if ($result) {
                //判断次数，昨天归1
                if ($result['create_time'] <= $sendTime) {
                    $data['count'] = 1;
                } else {
                    $data['count'] = array('exp', 'count+1');
                }
                $result = M('Sms')->where(['phone' => $phone])->save($data);
            } else {
                $data['phone'] = $phone;
                $data['count'] = 1;
                $result = M('Sms')->add($data);
            }
            if ($result !== false) {
                $this->jsonReturn(1, '验证码发送成功');
            } else {
                $this->jsonReturn(0, '验证码发送失败');
            }
        } else {
            $this->jsonReturn(0, '验证码发送失败');
        }
    }

    /**
     * 根据type查询具体id
     * @param $type int 小汽车1,客运2,货运3
     * @return mixed
     */
    protected function getScopeTypeByType($type){
        $type=intval($type);
        //将type映射到实际的id，小汽车1对应1，客运2对应2（客运）和4（客运和货运），货运3对应3（货运）和4（客运和货运）
        switch ($type){
            case 2 : $scopeType=[2,4];break;
            case 3 : $scopeType=[3,4];break;
            default : $scopeType=[1];
        }
        return $scopeType;
    }

    /**
     * 通过经纬度获取表中的城市名和id
     * @param $lat string 纬度
     * @param $long string 经度
     * @return mixed
     */
    protected function getSite($lat,$long){
        $url="http://api.map.baidu.com/geocoder/v2/?output=json&ak=hAYmqBGieMziaFEq8fX6GbGnsEdVFVng&location=$lat,$long";
        $result=$this->requestByGet($url);
        $result=json_decode($result,true);
        if($result['status']===0){
            $cityName=$result['result']['addressComponent']['city'];
            $city=M('Region')->where(['name'=>$cityName,'level'=>2])->field('id,name')->find();
            if($city){
                return $city;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 返回是否有下一页形式的数组
     * @param array $arr
     * @return array
     */
    protected function checkEndPage(array $arr){
        if(count($arr)<$this->pageLimit+1){
            $is_end='1';
        }else{
            $is_end='0';
            array_pop($arr);
        }
        return ['is_end'=>$is_end,'list'=>$arr];
    }

    /**
     * 计算距离sql语句
     * @param $lat
     * @param $long
     * @return string
     */
    public function getDistanceSql($lat,$long){
        return "round(6378.138*2*asin(sqrt(pow(sin(
($lat*pi()/180-`lat`*pi()/180)/2),2)+cos($lat*pi()/180)*cos(`lat`*pi()/180)*
pow(sin( ($long*pi()/180-`long`*pi()/180)/2),2)))*1000)";
    }

    /**
     *  检测是否装修完成
     *  @param $id int 商户id
     *  @return bool
     */
    protected function checkBusinessFixed($id){
        $id=intval($id);
        $business=M('Business')->where(['id'=>$id])->find();
        if($business){
            //是否填写基本资料
            if(empty($business['name'])){
                return false;
            }
            //是否填写经纬度
            if(empty($business['lat'])){
                return false;
            }
            //是否上传轮播图
            $images=M('BusinessSlide')->where(['business_id'=>$id])->find();
            if(!$images){
                return false;
            }
            $services=M('BusinessService')->where(['business_id'=>$id,'is_deleted'=>0])->find();
            if(!$services){
                return false;
            }
            return true;
        }else{
            return false;
        }
    }

    /**
     *  修改装修完成状态
     *  @param $id int 商户id
     *  @return bool
     */
    protected function setBusinessFixed($id){
        $id=intval($id);
        $business=M('Business')->where(['id'=>$id,'status'=>5])->find();
        //改未装修状态
        if($business){
            $r=$this->checkBusinessFixed($business['id']);
            if($r){
                $result=M('Business')->where(['id'=>$id])->save(['status'=>1]);
                if($result!==false){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}